package com.yami.shop.common.storage;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.enums.QiniuZone;
import com.yami.shop.common.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author mengcy 2020-06-20
 */
public class QiniuStorage implements IStorage{

    private Qiniu qiniu;

    private Configuration configuration;

    private UploadManager uploadManager;

    private BucketManager bucketManager;

    private Auth auth;

    public QiniuStorage(Qiniu qiniu){
        this.qiniu = qiniu;
        Zone zone = null;
        if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_BEI)) {
            zone = Zone.huabei();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_DONG)) {
            zone = Zone.huadong();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_NAN)) {
            zone = Zone.huanan();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.BEI_MEI)) {
            zone = Zone.beimei();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.XIN_JIA_PO)) {
            zone = Zone.xinjiapo();
        }
        configuration = new Configuration(zone);
        uploadManager = new UploadManager(configuration);
        auth = Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
        bucketManager = new BucketManager(auth, configuration);
    }

    @Override
    public String getPrefixUrl() {
        return qiniu.getResourcesUrl();
    }

    @Override
    public String upload(String fileName, byte[] bytes) throws Exception {
        String upToken = auth.uploadToken(qiniu.getBucket(), fileName);
        Response response = uploadManager.put(bytes, fileName, upToken);
        Json.parseObject(response.bodyString(),  DefaultPutRet.class);
        return fileName;
    }

    @Override
    public void delete(String fileName) throws Exception {
        bucketManager.delete(qiniu.getBucket(), fileName);
    }
}
